package chap_01_CompletableFuture.step_03_interrupt;

import java.util.concurrent.TimeUnit;

/**
 * @Description 借助多线程之间的volatile共享变量，来实现线程的中断、停止
 * @Author shihan
 * @Date 2022/10/22 15:45
 * @Version 1.0
 */
public class InterruptDemo_01_Volatile {

    static volatile boolean isStop = false;

    public static void main(String[] args) {
        new Thread(() -> {
            // 需要不断地 while 循环去判断 volatile 变量的值，增加消耗
            while (true) {
                if (isStop) {
                    System.out.println(Thread.currentThread().getName() + "线程识别到volatile变量的修改，终止！");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "正在运行...");
            }
        }, "t1").start();

        new Thread(() -> {
            isStop = true;
            System.out.println(Thread.currentThread().getName() + "对volatile变量进行修改！");
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程结束！");
    }

}
